package com.example.service;

import com.example.dao.BillDao;
import com.example.dao.CustomerDao;
import com.example.dao.RuleDao;
import com.example.pojo.*;
import com.ql.util.express.DefaultContext;
import com.ql.util.express.ExpressRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class DiscountService {
    @Autowired
    private CustomerDao customerDao;

    @Autowired
    private RuleDao ruleDao;
    @Autowired
    private BillDao billDao;

    public Customer getCustomer(String idCard) {
        return customerDao.findByIdCard(idCard);
    }
    public Customer getCustomer(Long id) {
        return customerDao.findById(id);
    }
    public Object getVIP(Object o) {
        return o;
    }

    public BigDecimal discount(String vipLevel, String itemName, BigDecimal price) throws Exception {
        VipRule vipRule = ruleDao.findRulesByLevel(vipLevel);
        if (vipRule == null) {
            throw new Exception("vipRule is null");
        }
        List<Rule> ruleList = ruleDao.findRulesByVipRuleId(vipRule.getId());
        BigDecimal currentPrice = price;
        for (Rule rule : ruleList
        ) {
            ExpressRunner runner = new ExpressRunner();
            DefaultContext<String, Object> context = new DefaultContext<String, Object>();
            String express = rule.getExpress();
            context.put("价格", price);
            Object r = runner.execute(express, context, null, true, false);
            currentPrice = BigDecimal.valueOf(Double.valueOf(String.valueOf(r)));
        }
        return currentPrice;
    }

    public List<Bill> findBillByCustomerId(Long customerId) {
        List<Bill> billList = billDao.findBillByCustomerId(customerId);
        for (Bill bill : billList
        ) {
            Long id = bill.getId();
            List<BillItem> billItemList = billDao.findBillItemsByBillId(id);
            bill.setBillItemList(billItemList);
        }
        return billList;
    }
}
